<template>
    <div class="manageofmass_layout">
        <ZWArticlesHeader v-if="showHeader" v-bind="articlesData" />
        <div class="container">
            <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
            <ZwTable
                ref="tableRef"
                class="table-box"
                tab-h="initial"
                :option="tableOption"
                :fetch-params="state.searchParams"
                :fetch-api="fetchApi()"
                @dataChange="onDataChange">
                <template #headerOperate>
                    <el-button class="high_btn" @click="highSet">高级设置</el-button>
                    <el-dropdown v-auth="'NEW_CUST_GP'">
                        <el-button class="add_btn" type="primary" :icon="Plus">新建客户群发</el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item disabled>短信群发</el-dropdown-item>
                                <el-dropdown-item divided @click="jump2Customer">企微客户群发</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </template>
            </ZwTable>
        </div>
        <ZWDeletdialog ref="DeletdialogRef" @submit="del" />
        <!-- 提醒弹框 -->
        <ZWRemid ref="ZWRemidRef" @submit="remindConfirm" />
        <!-- 预览抽屉层 -->
        <ZWDrawer ref="DrawerRef">
            <div class="preview">
                <div class="prev_box">
                    <PhonePreview
                        ref="phonePreviewRef"
                        :input-content-data="inputContentData"
                        :material-content-data="materialContentData" />
                </div>
                <div class="pre_list">
                    <ul class="pre_main">
                        <li v-for="(item, index) in cus_info" :key="index" class="pre_list_item">
                            <template v-if="item.children && custFilterType == 2">
                                <template
                                    v-if="
                                        custInfo.cust_filter_json.sync_wx_type == 2 ||
                                        custInfo.cust_filter_json.sync_wx_type == 1
                                    ">
                                    <span class="pre__item_label">{{ item.name }}</span>
                                    <div class="send_box_wrap">
                                        <div v-for="(v, key) in item.children" :key="key" class="send_box">
                                            <span class="send_box_name">{{ v.name }}</span>
                                            <span class="send_box_content">
                                                {{ custInfo[item.content][v.content] || '-' }}
                                            </span>
                                        </div>
                                    </div>
                                </template>
                            </template>
                            <template v-else-if="item.content == 'cust_filter_json'">
                                <span class="pre__item_label">{{ item.name }}</span>
                                <span class="pre_item_con">全部企微客户</span>
                            </template>
                            <template v-else>
                                <span class="pre__item_label">{{ item.name }}</span>
                                <span class="pre_item_con">{{ custInfo[item.content] || '-' }}</span>
                            </template>
                        </li>
                    </ul>
                </div>
            </div>
            <template #bottom>
                <el-button @click="exportCustomer">导出客户</el-button>
                <el-button type="primary" @click="remindConfirm">一键提醒未发送员工</el-button>
            </template>
        </ZWDrawer>
        <ZWadvancedSetup ref="advanced" :type="2"></ZWadvancedSetup>
        <!-- 未/已发送员工弹窗 -->
        <ZWSendDialog ref="sendDialogRef"></ZWSendDialog>
    </div>
</template>

<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import ZWadvancedSetup from '@/components/ZWadvancedSetup.vue';
import ZWRemid from '../../components/ZWRemid.vue';
import ZWDrawer from '../../components/ZWDrawer.vue';
import PhonePreview from '@/components/zw/phonePreview/welcomePhonePreview/materialPreview/index.vue';
import ZWArticlesHeader from '@/components/ZWArticlesHeader.vue';
import ZWSendDialog from '../components/ZWSendDialog.vue';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { ref, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import { deepCopy } from '@/utils/helper';
import { getSetionId, getVideoImage, IsNotEmpty, tableH, reSize, initMaterialData } from '@/utils/utils';
import { customerListData, customerInfo, customerRemind, customerDel, customerExport } from '@/api/channel/index';
import { getCreateList } from '@/api/common';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';

const DeletdialogRef: any = ref(null);
const router = useRouter();
const advanced: any = ref(null);
const phonePreviewRef = ref<HTMLElement | null>();
const inputContentData = ref<string>(''); //  用户存放回显数据  欢迎语输入框
const materialContentData = ref<Array<any>>([]);
const defaultParams = {
    title: '', //标题
    release_channel: '-1', //发布渠道
    created_uids: [], //群主/创建人
    createTime: [] //创建时间
};

const articlesData = {
    title: '客户群发',
    desc: `<div>企业统一创建群发内容，可通过不同渠道例如短信、微信等发起活动及福利等直接触达到客户。
        <br />客户短信群发：短信统一编辑及精准触达到客户；<br />
        客户微信消息群发：企微通过微信消息通知员工，员工在企微端确认群发给客户。同一个员工向同一个客户每天最多可群发1条消息。</div>`,
    url: '/static/channel/cutomer_send.png'
};

/**
 * 发送类型1-全部，2-条件筛选
 */
const custFilterType = ref<any>('');

const tableRef = ref<HTMLElement | null>(null);
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '群发标题',
            name: 'title',
            value: '',
            type: 'input',
            placeholder: '请输入群发标题'
        },
        {
            label: '发布渠道',
            name: 'release_channel',
            value: '-1',
            type: 'select',
            placeholder: '请选择发布渠道',
            optionList: [
                {
                    label: '全部',
                    value: '-1'
                },
                {
                    label: '短信',
                    value: '1',
                    disabled: true
                },
                {
                    label: '企微',
                    value: '2'
                }
            ]
        },
        {
            label: '创建人',
            name: 'created_uids',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone}) `;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '下发日期',
            name: 'createTime',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        }
    ];
});
const search = (v: any) => {
    state.searchParams = { ...deepCopy(defaultParams), ...v };
};
const reset = (v: any) => {
    state.searchParams = { ...deepCopy(defaultParams) };
};

// 表格
const tableOption = [
    {
        prop: 'title',
        label: '群发标题',
        minWidth: 200,
        fixed: 'left',
        showOverflowTooltip: true
    },
    {
        prop: 'release_channel',
        label: '渠道',
        width: 110,
        showOverflowTooltip: true,
        render({ row }: any) {
            // 0-未知渠道
            return ['--', '企微', '短信'][row.release_channel];
        }
    },
    {
        prop: 'sync_wx_type',
        label: '发送方式',
        width: 150,
        render({ row }: any) {
            return ['', '立刻发送', '指定时间发送'][row.sync_wx_type];
        }
    },
    {
        prop: 'sync_wx_time',
        label: '下发时间',
        minWidth: 180
    },
    {
        prop: 'user_name',
        label: '创建人',
        width: 140
    },
    {
        prop: 'customer_total_num',
        label: '客户总数',
        width: 120
    },
    {
        prop: 'work_user_not_send_num',
        label: '未发送员工',
        width: 120,
        render({ row }: any) {
            const num = row.work_user_not_send_num || 0;
            return (
                <>
                    <div vShow={num > 0} class="text-custom-primary" onClick={() => handleSendDialog(row, 1)}>
                        {num}
                    </div>
                    <div vShow={num == 0}>{num}</div>
                </>
            );
        }
    },
    {
        prop: 'work_user_send_num',
        label: '已发送员工',
        width: 120,
        render({ row }: any) {
            const num = row.work_user_send_num || 0;
            return (
                <>
                    <div vShow={num > 0} class="text-custom-primary" onClick={() => handleSendDialog(row, 2)}>
                        {num}
                    </div>
                    <div vShow={num == 0}>{num}</div>
                </>
            );
        }
    },
    {
        prop: 'customer_deliver_num',
        label: '送达客户',
        width: 120
    },
    {
        prop: 'customer_not_deliver_num',
        label: '未送达客户',
        width: 100
    },
    {
        prop: 'operate',
        label: '操作',
        width: 286,
        fixed: 'right',
        isOperate: true,
        option: [
            {
                name: '提醒',
                authCode: 'REMIND_GP',
                disabledFn: (row: any) => {
                    return !row.work_user_not_send_num;
                },
                click: (row: any) => {
                    remind(row);
                }
            },
            {
                name: '预览',
                authCode: 'PREVIEW_GP',
                click: (row: any) => {
                    preInfo(row);
                }
            },
            {
                name: '复制',
                authCode: 'COPY_GP',
                click: (row: any) => {
                    const path = '/channel/managetomass/customergroup/manageofmass';
                    const query = { id: row.id };
                    router.push({ path, query });
                }
            },
            {
                name: '删除',
                authCode: 'DEL_GP',
                click: (row: any) => {
                    remove(row);
                }
            }
        ]
    }
];
const showHeader = ref<boolean>(false);
const showTop = (data?: any) => {
    if (IsNotEmpty(data)) {
        if (
            IsNotEmpty(data?.created_uids?.length) ||
            IsNotEmpty(data?.createTime) ||
            data?.release_channel != '-1' ||
            IsNotEmpty(data?.title)
        ) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
};
const onDataChange = (data: any) => {
    showHeader.value = !showTop(state.searchParams) && data.total <= 0;
};
const fetchApi = () => {
    // 获取文件列表
    // return getFissionList
    return customerListData;
};
// 刷新表格
const reloadTable = () => {
    tableRef.value.reload();
};
// 选中的id
const selfSelectId = ref(0);
const ZWRemidRef = ref<any>(null);
// 预览
const DrawerRef = ref<any>(null);
const FriendDetail = ref([]);
const getChannel = (val: any) => {
    return ['短信', '企微', '短信'][val];
};
// 导出客户
const exportCustomer = e => {
    customerExport({
        send_msg_id: selfSelectId.value
    }).then((res: any) => {
        DrawerRef.value.drawer = false;
        parabolaAnimation(e);
        ShowTaskMessage('导出客户异步任务创建成功');
    });
};
const custInfo = ref({
    cust_filter_json: {
        sync_wx_type: 0,
        create_time: '',
        customer_tag_name: '',
        remove_customer_tag_name: '',
        work_department_name: ''
    },
    release_channel: {},
    release_channelStr: {},
    statusStr: {},
    taskSchedule: {},
    user_name: {},
    not_send_staff: 0,
    undelivered_cust_count: 0,
    create_time: '',
    cust_count: 0
});
const cus_info = reactive([
    { name: '任务状态：', content: 'statusStr' },
    { name: '任务进度：', content: 'taskSchedule' },
    { name: '渠道：', content: 'release_channelStr' },
    {
        name: '发送范围：',
        content: 'cust_filter_json',
        children: [
            { name: '添加员工：', content: 'work_department_name' },
            { name: '添加时间：', content: 'create_time' },
            { name: '客户标签：', content: 'customer_tag_name' },
            { name: '排除客户标签：', content: 'remove_customer_tag_name' }
        ]
    },
    { name: '创建人：', content: 'user_name' },
    { name: '所在部门：', content: 'user_departName' },
    { name: '创建时间：', content: 'create_time' },
    { name: '预计发送客户为：', content: 'cust_count' },
    { name: '未发送员工：', content: 'not_send_staff' },
    { name: '未触达客户：', content: 'undelivered_cust_count' }
]);
const preInfo = async (val: any) => {
    selfSelectId.value = val.id;
    try {
        const res: any = await customerInfo({
            send_msg_id: val.id
        });
        custInfo.value = {
            cust_filter_json: {
                sync_wx_type: res.sync_wx_type,
                create_time: res.cust_filter_json ? res.cust_filter_json?.create_time : '',
                customer_tag_name: res.cust_filter_json
                    ? getSetionId('name', res.cust_filter_json?.customer_tag).join(' ')
                    : '',
                remove_customer_tag_name: res.cust_filter_json
                    ? getSetionId('name', res.cust_filter_json?.remove_customer_tag).join(' ')
                    : '',
                work_department_name: res.cust_filter_json
                    ? getSetionId('name', res.cust_filter_json?.work_user).join(' ')
                    : ''
            },
            release_channel: res.release_channel,
            release_channelStr: getChannel(res.release_channel),
            statusStr: ['', '未开始', '进行中', '已完成', '失败'][res.status],
            taskSchedule: res.progress_rate + '%',
            user_name: res.user_name,
            user_departName: IsNotEmpty(res.user_local_department)
                ? getSetionId('name', res.user_local_department).join(' ')
                : '--',
            not_send_staff: (res.not_send_staff || 0) + '人',
            undelivered_cust_count: (res.undelivered_cust_count || 0) + '个',
            create_time: res.created_at,
            cust_count: (res.cust_count || 0) + '个'
        };
        inputContentData.value = res.welcome_info.welcome_text;
        materialContentData.value = initMaterialData(res.welcome_info.welcome_material);
        DrawerRef.value.drawer = true;
        DrawerRef.value.width = 430;
        DrawerRef.value.title = val.title ? `预览【${val.title}】群发` : '';
        custFilterType.value = res.cust_filter_type;
    } catch (e) {}
};

const sendDialogRef = ref();
/**
 * @description: 发送员工弹窗
 * @param {*} row 当前行数据
 * @param {*} type 1已发送 0未发送
 * @return {*}
 */
const handleSendDialog = (row: any, type: any) => {
    sendDialogRef?.value?.handleOpen(row, type);
};

// 删除
const remove = (val: any) => {
    selfSelectId.value = val.id;
    DeletdialogRef.value.appDialog.visible = true;
};
// 删除确认
const del = async () => {
    customerDel({
        send_msg_id: selfSelectId.value
    }).then((res: any) => {
        ElMessage.success(`删除成功`);
        DeletdialogRef.value.appDialog.visible = false;
        reloadTable();
    });
};
// 提醒
const remind = (val: any) => {
    selfSelectId.value = val.id;
    ZWRemidRef.value.appDialog.visible = true;
    ZWRemidRef.value.content = `<div>您将提醒到<span style="color:#FF6B00"> ${val.work_user_not_send_num} </span>位未发送的员工，</div><div>点击确认后一键提醒。</div>`;
};
// 提醒确认
const remindConfirm = () => {
    customerRemind({
        send_msg_id: selfSelectId.value
    }).then((res: any) => {
        ElMessage.success('提醒成功');
        ZWRemidRef.value.appDialog.visible = false;
    });
};

// 高级设置
const highSet = () => {
    advanced.value.isShow = true;
};
//创建
const jump2Customer = () => {
    router.push('/channel/managetomass/customergroup/manageofmass');
};
</script>

<style lang="scss">
.text-custom-primary {
    color: var(--el-color-primary);
    cursor: pointer;
}
</style>
<style lang="scss" scoped>
.manageofmass_layout {
    height: calc(100vh - 142px);
    display: flex;
    flex-direction: column;

    .container {
        flex: 1;
        display: flex;
        flex-direction: column;
        padding: 24px;
        border: 1px solid #eaeaea;
        border-radius: 4px;
        box-sizing: border-box;
        background-color: #fff;
        overflow: hidden;

        .zw-table {
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow: hidden;

            :deep(.el-table) {
                flex: 1;

                .el-table__empty-block {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                }
            }
        }
    }
}

.dropdown_btn {
    margin-right: 10px;
}

.header_top {
    padding: 20px;
    box-sizing: border-box;
    height: 132px;
    background: #fff;
    border: 1px solid #eaeaea;
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header_top_l {
        display: flex;
    }

    .custom_avator {
        width: 100px;
        height: 100px;
        margin-right: 25px;
    }

    .custom_intro {
        margin-left: 15px;
    }

    .custom_desc {
        .custom_desc_title {
            margin-top: 10px;
            font-size: 20px;
            font-family: STHeitiSC-Medium, STHeitiSC;
            font-weight: 500;
            color: #33302d;
            line-height: 21px;
            margin-bottom: 6px;
        }

        .custom_desc_desc {
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            font-weight: 300;
            color: #696969;
            line-height: 18px;
        }
    }
}

.preview {
    .prev_box {
        flex: 1;
        display: flex;
        justify-content: center;
    }

    .pre_list {
        margin: 16px auto;
        width: 340px;
        background: #f7f7f7;
        border-radius: 1px;
        padding-left: 20px;
        padding-bottom: 1px;
        box-sizing: border-box;

        .pre_main {
            padding-top: 12px;

            .pre_list_item {
                margin-bottom: 16px;
                display: flex;
                font-size: 14px;
                font-family: STHeitiSC-Light, STHeitiSC;
                font-weight: 300;
                text-align: left;

                .pre__item_label {
                    display: inline-block;
                    width: 125px;
                    color: #969696;
                }

                .pre_item_con {
                    flex: 1;
                    color: #33302d;
                }
            }

            .send_box_wrap {
                flex: 1;
            }

            .send_box {
                display: flex;
                width: 115%;
                font-size: 12px;
                font-family: STHeitiSC-Light, STHeitiSC;
                font-weight: 300;
                transform: scale(0.85);
                transform-origin: left top;
                margin-bottom: 6px;
                color: #33302d;

                .send_box_name {
                    display: inline-block;
                    width: 80px;
                    white-space: nowrap;
                }

                .send_box_content {
                    flex: 1;
                }
            }
        }
    }
}

.high_btn {
    margin-right: 14px;
}
</style>
